package com.example.blog.ws.config;

import com.example.blog.util.TokenUtil.decryptToken;
import com.example.blog.util.TokenUtil.spiltUtils;

import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import java.util.List;
import java.util.Map;

public class GetHttpSessionConfig extends ServerEndpointConfig.Configurator {

    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        Map<String, List<String>> headers = request.getHeaders();
        List<String> cookieList = headers.get("cookie");
        if (cookieList != null && !cookieList.isEmpty()) {
            String cookies = cookieList.get(0);
            String[] cookieArray = cookies.split(";");
            for (String cookie : cookieArray) {
                if (cookie.trim().startsWith("token=")) {
                    String token = cookie.trim().substring("token=".length());
                    String pe = decryptToken.decrypt(token);
                    String userName = spiltUtils.getUserName(pe);
                    sec.getUserProperties().put("userName", userName);
                    break;
                }
            }
        }
    }
}

